from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from order_app.models import OrderInfo
from user_app.serializers.order import OrderSerializer
from utils.rest_pagination import MyPagination


class OrderView(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderSerializer
    pagination_class = MyPagination

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword', '')
        result = OrderInfo.objects.filter(order_id__contains=keyword)
        return result

    def update(self, request, *args, **kwargs):
        order_id = kwargs.get('pk', '')
        status = kwargs.get('status', '')

        try:
            instance = self.queryset.get(order_id=order_id)
        except OrderInfo.DoesNotExist:
            return Response("order_id 不存在")

        data = {'order_id': order_id, 'status': status}

        ser = self.get_serializer(instance, data=data)
        ser=OrderSerializer(instance, data=data)
        ser.is_valid(raise_exception=True)
        self.perform_update(ser)
        return Response(ser.data)
